package com.yeyks.common.annotation.validator;

import com.yeyks.common.annotation.EmailCheck;
import com.yeyks.common.annotation.util.DisposeStrUtils;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.util.regex.Pattern;

/**
 * @author fuchangshuai
 * @date 2019/06/24 11:19
 */
public class EmailValidator implements ConstraintValidator<EmailCheck, String> {
    private Pattern pattern = Pattern.compile("\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*");

    @Override
    public void initialize(EmailCheck constraintAnnotation) {

    }

    @Override
    public boolean isValid(String email, ConstraintValidatorContext constraintValidatorContext) {
        if (DisposeStrUtils.strNotEmpty(email)) {
            if (!pattern.matcher(email).matches()) {
                //禁用默认的message的值
                constraintValidatorContext.disableDefaultConstraintViolation();
                //重新添加错误提示语句
                constraintValidatorContext.buildConstraintViolationWithTemplate("邮箱格式不正确").addConstraintViolation();
                return false;
            }
            return true;
        }
        return false;
    }
}
